package ssm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ssm.mapper.BookMapper;
import ssm.mapper.CartMapper;
import ssm.mapper.UserMapper;
import ssm.pojo.Book;
import ssm.pojo.Cart;
import ssm.pojo.CartItem;
import ssm.pojo.User;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserSerivce {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CartMapper cartMapper;

    public User getUser(String uname,String password){
        User user = userMapper.getUser(uname, password);
        if (user==null){
            return null;
        }
        List<CartItem> cartItemList = cartMapper.getCartItem(user.getUid());
        Map<Integer,CartItem> cartItemMap = new HashMap<>();
        for(CartItem cartItem:cartItemList){
            cartItemMap.put(cartItem.getBook().getBid(),cartItem);
        }
        Cart cart = new Cart(cartItemMap);
        user.setCart(cart);
        return user;
    }

    public User getUserByName(String uname) {

        return userMapper.getUserByName(uname);
    }

    public void saveUser(User user) {
        userMapper.addUser(user);
        return;
    }
}
